#include<iostream>
#include<sys/types.h>
#include<sys/socket.h>
#include<unistd.h>
#include<arpa/inet.h>
#include<netinet/in.h>
#include<string>
#include<cstring>

static int Listen_size=5;

enum
{
    sockert_create=1,
    bind_fase,
    listen_false,
};

class Sock
{
public:
    Sock() {}

    void Socket()
    {
        fd_=socket(AF_INET,SOCK_STREAM,0);
        if(fd_<0)
        {
            std::cout<<"sockert create "<<std::endl;
            exit(sockert_create);
        }
    }

    void Bind(uint16_t port)
    {
        struct sockaddr_in local;
        memset(&local,0,sizeof(local));
        local.sin_family=AF_INET;
        local.sin_addr.s_addr = INADDR_ANY;
        local.sin_port=htons(port);
        if(bind(fd_,(struct sockaddr*)&local,sizeof(local))<0)
        {
            std::cout<<"bind false"<<std::endl;
            exit(bind_fase);
        }
    }

    void Listen()
    {
        if(listen(fd_,Listen_size)<0)
        {
            std::cout<<"listen fase"<<std::endl;
            exit(listen_false);
        }
    }

    int Accept(std::string *client_ip,uint16_t *client_port)
    {
        struct sockaddr_in client;
        socklen_t len=sizeof(client);
        int newfd=accept(fd_,(struct sockaddr*)&client,&len);
        if(newfd<0)
        {
            std::cout<<"accept false"<<std::endl;
        }
        char ipstr[64];
        inet_ntop(AF_INET, &client.sin_addr, ipstr, sizeof(ipstr));
        *client_ip = ipstr;
        return newfd;
    }

     bool Connect(const std::string &ip, const uint16_t &port)
    {
        struct sockaddr_in peer;
        memset(&peer, 0, sizeof(peer));
        peer.sin_family = AF_INET;
        peer.sin_port = htons(port);
        inet_pton(AF_INET, ip.c_str(), &(peer.sin_addr));

        int n = connect(fd_, (struct sockaddr*)&peer, sizeof(peer));
        if(n == -1) 
        {
            std::cerr << "connect to " << ip << ":" << port << " error" << std::endl;
            return false;
        }
        return true;
    }

     void Close()
    {
        close(fd_);
    }

    int Fd()
    {
        return fd_;
    }
    ~Sock()
    {
        close(fd_);
    }
private:
    int fd_;
};